package judesart.app.repository;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import judesart.app.domain.Gallery;
import judesart.app.domain.Image;
import judesart.app.shared.ValidationException;
import judesart.app.validation.AppValidator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class ImageDAOImpl implements ImageDAO {
    private final static Log LOGGER = LogFactory.getLog(ImageDAOImpl.class);

    @PersistenceContext
    private EntityManager entityManager;

    @Inject
    private AppValidator validator;

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public Image createImage(Image image) {
        entityManager.persist(image);
        entityManager.flush();
        return image;
    }
    
    @Transactional(propagation = Propagation.REQUIRED)
    public Image updateImage(Image image) {
        image = entityManager.merge(image);
        entityManager.flush();
        return image;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public synchronized Image findImageById(Long imageId) {
        Image image = entityManager.find(Image.class, imageId);
        if (image != null) {
            image.getData();
        }
        return image;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public Image deleteImage(Long id) {
        Image image = entityManager.find(Image.class, id);
        if (image != null) {
            entityManager.remove(image);
            entityManager.flush();
        }
        return image;
    }

}
